import React from 'react';
import { TColumn, EditorType } from '@/components/editable-excel-table';
import { TableAction, TableState } from '../reducer/types';
import { EditableExcelTableI18n } from '../i18n';

export const TableContext = React.createContext<{
    state: TableState<TColumn>;
    dispatch: React.Dispatch<TableAction<TColumn>>;
    i18n: EditableExcelTableI18n;
    editorRenderers?: Partial<
        Record<
            EditorType,
            {
                editableRender: React.FC<{ value: any; onChange: (value: any) => void }>;
                readonlyRender?: React.FC<{ value: any; onChange: (value: any) => void }>;
            }
        >
    >;
} | null>(null);

export function useTableContext() {
    const ctx = React.useContext(TableContext);
    if (!ctx) throw new Error('TableContext is not available');
    return ctx;
}

/**
 * 类型安全的 dispatch 包装函数
 * 解决泛型组件中 dispatch 类型不匹配的问题
 */
export function createTypedDispatch<C extends TColumn>(
    dispatch: React.Dispatch<TableAction<TColumn>>
): React.Dispatch<TableAction<C>> {
    return dispatch as React.Dispatch<TableAction<C>>;
}
